﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using VBACodeingTool.Module;
using static VBACodeingTool.VBEHelper;

namespace VBACodeingTool
{
    public static class FromHelper
    {
        #region Popup

        private static Popup CreatePopup()
        {
            ProgramInstanceManager.Popup.CloseWindow();
            Popup popup = new Popup();
            ProgramInstanceManager.Popup = popup;
            MouseHelper.GetCaretPosition(out int X, out int Y);
            popup.X = X;
            popup.Y = Y;
            popup.TopMost = true;
            return popup;
        }

        public static Popup ShowPopup()
        {
            Popup popup = CreatePopup();
            popup.Show();
            VBEHelper.GetCurrentCodePane().Window.SetFocus();
            return popup;
        }

        public static Popup ShowPopup(List<ProjectCodeData> codeData)
        {
            if (codeData.Count < 0)
            {
                return CreatePopup();
            }
            Popup popup = CreatePopup();
            popup.AllContents = codeData;
            if (codeData.Count > 0)
            {
                Debug.WriteLine("窗口显示了");
                popup.Show();
            }
            VBEHelper.GetCurrentCodePane().Window.SetFocus();
            return popup;
        }

        public static void HitCode(Keys vkCode)
        {
            ShortCutAndPosition shortCutAndPosition = VBEHelper.GetShortCut();
            CodeAndPosition codeAndPosition = shortCutAndPosition.selfCodeAndPosition;
            string shortCut = shortCutAndPosition.shortCut;
            if (shortCut == null)
            {
                return;
            }
            if (shortCut.Length < 0 || string.IsNullOrEmpty(shortCut))
            {
                ProgramInstanceManager.Popup.CloseWindow();
            }
            if (RegexManager.EnglishContain.Matches(vkCode.ToString()).Count == 1 || vkCode == Keys.Back)
            {
                if (vkCode != Keys.Back)
                {
                    shortCut += vkCode.ToString();
                }
                if (!codeAndPosition.IsMultiLines && !string.IsNullOrEmpty(shortCut))
                {
                    ProjectCodeModule projectCodeModule = CodeLoaderHelper.GetCurrentModuleProjectData();
                    if (projectCodeModule != null)
                    {
                        ProgramInstanceManager.CodeDataManager.UpData(projectCodeModule.CodeName, projectCodeModule.ProjectCodeData);
                        FromHelper.ShowPopup(ProgramInstanceManager.CodeDataManager.GetShowCodeData(shortCut));
                    }
                }
            }
        }

        #endregion Popup
    }
}